#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include<sys/reboot.h>
#include "../thirdparty/log.h"
#include "daemon_sub_process.h"

#define MAX_FAILED_COUNT 5
#define GATEWAY_BIN "/usr/bin/gateway"
/**
 * @brief 初始化子进程
 * 
 * @param cmd 子进程命令
 * @return sub_process_t* 子进程结构体指针
 */
sub_process_t *daemon_sub_process_Init(char *cmd)
{
    /*1.给子进程结构体分配内存*/

    sub_process_t* process = (sub_process_t*)malloc(sizeof(sub_process_t) * 1);
    if (process == NULL)
    {
        log_error("sub_process mem malloc fail\n");
        return NULL;
    }
    /*2.初始化子进程各项参数*/
    process->cmd = cmd;
    process->pid = -1;
    process->failed_count = 0;
    
    return process;
}

int daemon_sub_process_check_start(sub_process_t *process)
{
    /*1.检查子进程状态*/
    int over_status = 0;
    
    if (process->pid == -1 || waitpid(process->pid,&over_status,WNOHANG) == -1)
    {
        /*2判断进程是不是非正常的挂掉了*/
        if (over_status != 0)   //非正常挂掉
        {
            /*2.1统计非正常挂掉的次数*/
            process->failed_count++;
            /*2.2若达到限制的最大次数就重启程序*/
            if (process->failed_count >= MAX_FAILED_COUNT)
            {
                reboot(RB_AUTOBOOT);
            }
                      
        }
        /*3.重新起一个子进程*/
        process->pid = fork();

        /*4.编写子进程执行的逻辑*/
        if (process->pid == 0)
        {
            /*4.1运行子进程*/
            char* main_cmd = GATEWAY_BIN;
            char* cmd_args[] = {main_cmd,process->cmd,NULL};
            char* envp[] = {NULL};
            int res = execve(main_cmd,cmd_args,envp);

            if (res == -1)
            {
                perror("execve\n");
                _exit(EXIT_FAILURE);
            }
            
        }
        
        
    }
    
    return 0;
}

void daemon_sub_process_destroy(sub_process_t *process)
{
    kill(process->pid,SIGTERM);
    waitpid(process->pid,NULL,0);
    printf("process stop :%s\n",process->cmd);
    free(process);
}
